package databases

import (
	"github.com/go-xorm/xorm"
	"github.com/juju/errgo/errors"
	"gitlab.gaodun.com/golib/gderror"
	"permission/config"
	"permission/vigo_loger"
)

type DepartFactory struct {
	Table        Tpo_Sys_Departments
	engine       *xorm.Engine
	RowsSlicePtr []Tpo_Sys_Departments
	DepartUserLeader   []DepartLeader
}

// 返回 user factory
func NewDepartFactory() *DepartFactory {
	funcFac := DepartFactory{}
	funcFac.engine, _ = config.InitEng()
	return &funcFac
}

// 根据 ids 查询列表
func (df *DepartFactory) FindInfoByDepartIds(departmentIds ...int64) error {
	df.RowsSlicePtr = []Tpo_Sys_Departments{}
	if len(departmentIds) == 0 {
		return errors.New("departmentIds is null")
	}
	err := df.engine.In("DeparentId", departmentIds).Where(" IsDelete != ?", 1).Find(&(df.RowsSlicePtr))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}
	return err
}

// 根据父 id 查询子节点
func (df *DepartFactory) FindInfoByParentId(departParentId int64) error {
	err := df.engine.Where(" ParentId = ? and IsDelete != ?", departParentId, 1).Find(&(df.RowsSlicePtr))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}
	return err
}

// all
func (df *DepartFactory) FindAllInfo() error {
	// 清空之前数据
	df.RowsSlicePtr = []Tpo_Sys_Departments{}
	err := df.engine.Where(" IsDelete != ? ", 1).Find(&(df.RowsSlicePtr))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}

	return err
}

func (df *DepartFactory) FindAllDepartUser() error {
	err := df.engine.Join("LEFT OUTER", "Tpo_Sys_Users", "Tpo_Sys_Users.UserID in (Tpo_Sys_Departments.leader_id)").Find(&(df.DepartUserLeader))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}

	return err
}

func (df *DepartFactory) FindByCampus(campusId, campusType int32) error {
	// 清空之前数据
	df.RowsSlicePtr = []Tpo_Sys_Departments{}
	err := df.engine.Where(" CampusType = ? and CampusLevelType = ?", campusId, campusType).Find(&(df.RowsSlicePtr))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}

	return err
}


func (df *DepartFactory) FindByErpId (erpId string) error {
	_, err := df.engine.Where("ErpDeparentId = ?", erpId).Get(&(df.Table))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}

	return err
}

func (df *DepartFactory) FindByLevel (CampusLevelType int32) error {
	err := df.engine.Where("CampusLevelType = ?", CampusLevelType).Find(&(df.RowsSlicePtr))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}

	return err
}
